﻿using System;
using System.Web;
using System.Web.Security;
using System.Web.UI.WebControls;

namespace Salient.Web.Administration.Security.Users
{
    public partial class editUser : SecurityPage
    {
        private Exception currentRequestException;

        public void AddAnother_Click(object sender, EventArgs e)
        {
            ResetUI();
            ((WebAdminWithConfirmation) Master).SetDisplayUI(false);
        }

        public void Cancel(object sender, EventArgs e)
        {
            ClearTextBoxes();
        }

        private void ClearTextBoxes()
        {
            UserID.Text = String.Empty;
            UserID.Enabled = true;
            Email.Text = String.Empty;
            Description.Text = String.Empty;
        }

        public void OK_Click(object sender, EventArgs e)
        {
            ReturnToPreviousPage(sender, e);
        }

        public void Page_Load()
        {
            string userName = CurrentUser;
            if (!IsPostBack)
            {
                PopulateCheckboxes();
                UserID.Text = userName;
                UserID.Enabled = false;

                var mu =
                    (MembershipUser)
                    CallWebAdminHelperMethod(true, "GetUser", new object[] {userName, false /* isOnline */},
                                             new[] {typeof (string), typeof (bool)});
                if (mu == null)
                {
                    return; // Review: scenarios where this happens.
                }
                Email.Text = mu.Email;
                ActiveUser.Checked = mu.IsApproved;
                string comment = mu.Comment;
                var notSet = (string) GetLocalResourceObject("NotSet");
                Description.Text = comment == null || comment == string.Empty ? notSet : mu.Comment;
            }
        }

        private void PopulateCheckboxes()
        {
            if (IsRoleManagerEnabled())
            {
                CheckBoxRepeater.DataSource = CallWebAdminHelperMethod(false, "GetAllRoles", new object[] {}, null);
                CheckBoxRepeater.DataBind();
                if (CheckBoxRepeater.Items.Count > 0)
                {
                    SelectRolesLabel.Text = (string) GetLocalResourceObject("SelectRoles");
                }
                else
                {
                    SelectRolesLabel.Text = (string) GetLocalResourceObject("NoRolesDefined");
                }
            }
            else
            {
                SelectRolesLabel.Text = (string) GetLocalResourceObject("RolesNotEnabled");
            }
        }

        public void ResetUI()
        {
            ClearTextBoxes();
        }

        public void ServerCustomValidate(object sender, ServerValidateEventArgs e)
        {
            if (currentRequestException == null)
            {
                e.IsValid = true;
                return;
            }
            var v = (CustomValidator) sender;
            v.ErrorMessage = currentRequestException.Message;
            e.IsValid = false;
        }

        public void SaveClick(object sender, EventArgs e)
        {
            UpdateUser(sender, e);
        }

        private void UpdateRoleMembership(string u)
        {
            if (u == null || u.Equals(String.Empty))
            {
                return;
            }
            foreach (RepeaterItem i in CheckBoxRepeater.Items)
            {
                var c = (CheckBox) i.FindControl("checkbox1");
                UpdateRoleMembership(u, c);
            }
            // Clear the checkboxes
            CurrentUser = null;
            PopulateCheckboxes();
        }

        private void UpdateRoleMembership(string u, CheckBox box)
        {
            // Array manipulation because cannot use Roles static method (need different appPath).
            string role = box.Text;

            bool boxChecked = box.Checked;
            var userInRole =
                (bool)
                CallWebAdminHelperMethod(false, "IsUserInRole", new object[] {u, role},
                                         new[] {typeof (string), typeof (string)});
            try
            {
                if (boxChecked && !userInRole)
                {
                    CallWebAdminHelperMethod(false, "AddUsersToRoles", new object[] {new[] {u}, new[] {role}},
                                             new[] {typeof (string[]), typeof (string[])});
                }
                else if (!boxChecked && userInRole)
                {
                    CallWebAdminHelperMethod(false, "RemoveUsersFromRoles", new object[] {new[] {u}, new[] {role}},
                                             new[] {typeof (string[]), typeof (string[])});
                }
            }
            catch (Exception ex)
            {
                PlaceholderValidator.IsValid = false;
                PlaceholderValidator.ErrorMessage = ex.Message;
            }
        }

        public void UpdateUser(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                return;
            }
            string userIDText = UserID.Text;
            string emailText = Email.Text;
            var notSet = (string) GetLocalResourceObject("NotSet");
            try
            {
                var mu =
                    (MembershipUser)
                    CallWebAdminHelperMethod(true, "GetUser", new object[] {UserID.Text, false /* isOnline */},
                                             new[] {typeof (string), typeof (bool)});
                mu.Email = Email.Text;
                if (
                    Description.Text != null && !Description.Text.Equals(notSet))
                {
                    mu.Comment = Description.Text;
                }

                mu.IsApproved = ActiveUser.Checked;

                string typeFullName = "System.Web.Security.MembershipUser, " + typeof (HttpContext).Assembly.GetName();
                ;
                Type tempType = Type.GetType(typeFullName);

                CallWebAdminHelperMethod(true, "UpdateUser", new object[] {mu}, new[] {tempType});
                UpdateRoleMembership(userIDText);
            }
            catch (Exception ex)
            {
                PlaceholderValidator.IsValid = false;
                PlaceholderValidator.ErrorMessage = ex.Message;
                return;
            }

            // Go to confirmation
            DialogMessage.Text = String.Format((string) GetLocalResourceObject("Successful"), userIDText);
            AddAnother.Visible = false;
            ((WebAdminWithConfirmation) Master).SetDisplayUI(true);

            ResetUI();
        }
    }
}